﻿Imports System.Text
Imports System.IO
Imports System.Management
Imports System.ComponentModel
Imports System.Net.Mail

Module Helper

    Public Function GenericCast(Of U, V)(ByVal obj As U) As V
        Try
            Return CType(DirectCast(obj, Object), V)
        Catch ex As InvalidCastException
            Return DirectCast(CompilerServices.Conversions.ChangeType(obj, GetType(V)), V)
        End Try
    End Function

    Public Function Serialize(Of T)(ByRef obj As T) As Byte()
        Dim SFormatter As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
        Dim my_stream As New IO.MemoryStream()
        SFormatter.Serialize(my_stream, obj)
        my_stream.Close()
        Return my_stream.ToArray()
    End Function

    Public Function Deserialize(Of T)(ByVal data() As Byte) As T
        Dim my_stream As New IO.MemoryStream(data)
        Dim SFormatter As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
        Dim Obj As T = SFormatter.Deserialize(my_stream)
        my_stream.Close()
        Return Obj
    End Function

    Public Function Deserialize(Of T)(ByVal my_stream As Stream) As T
        Dim SFormatter As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
        Dim Obj As T = SFormatter.Deserialize(my_stream)
        my_stream.Close()
        Return Obj
    End Function

    Public Function BytesToString(ByVal data() As Byte) As String
        Return BitConverter.ToString(data)
    End Function

    Public Function StringToBytes(ByVal data As String) As Byte()
        Dim elements() As String = Split(data, "-")
        Dim lst As New List(Of Byte)
        For Each item In elements
            Dim value As Byte = 0
            For i As Integer = 0 To item.Length - 1
                Dim v As Integer = 0
                Dim a As Byte = Asc(item.Chars(i))
                If a >= Asc("0") And a <= Asc("9") Then
                    v = a - Asc("0")
                Else
                    v = a - Asc("A") + 10
                End If
                value += v * Math.Pow(16, item.Length - i - 1)
            Next i
            lst.Add(value)
        Next item
        Return lst.ToArray()
    End Function

    Public Function GetRight(ByVal Source As String, ByVal Filter As String) As String
        Dim Tmp As String = ""
        If InStr(Source, Filter) = 0 Then
            Return ""
        Else
            Tmp = Right(Source, Len(Source) - InStr(Source, Filter) - Filter.Length + 1)
            Return Tmp
        End If
    End Function

    Public Function GetLeft(ByVal Source As String, ByVal Filter As String) As String
        Dim Tmp As String = ""
        If InStr(Source, Filter) = 0 Then
            Return ""
        Else
            Tmp = Left(Source, InStr(Source, Filter) - 1)
            Return Tmp
        End If
    End Function

End Module